package com.gtpickupapp;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.gtpickupapp.SearchSport.MyOnItemSelectedListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class CreateNewEvent extends Activity {
	final List<String> spinnerValue = new ArrayList<String>();
	private EditText mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;
    
    private EditText mTimeDisplay;
    private Button mPickTime;

    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 1;
    
    private EditText mEndTimeDisplay;
    private Button mEndPickTime;

    private int mEndHour;
    private int mEndMinute;

    static final int END_TIME_DIALOG_ID = 2;
    
    static final int DATE_DIALOG_ID = 0;
    
    public AlertDialog.Builder badName;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 View v = LayoutInflater.from(this.getParent()).inflate(R.layout.createnewevent, null);
		 setContentView(v);
		 
		 //Log.e("bundle test", getIntent().getExtras().getString("uName"));
		 //Log.e("bundle test", getIntent().getExtras().getString("location"));
		 
		 TextView location = (TextView) findViewById(R.id.create_sport_location);
		 location.setText("Location: " + getIntent().getExtras().getString("location"));
		 
		 mDateDisplay = (EditText) findViewById(R.id.create_sport_date);
		 mPickDate = (Button) findViewById(R.id.create_sport_date_button);
		 mPickDate.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));

		 mPickDate.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                showDialog(DATE_DIALOG_ID);
	            }
	        });
		 
		 
		 	mTimeDisplay = (EditText) findViewById(R.id.create_sport_begin_time_field);
		 	mTimeDisplay.requestFocus();
	        mPickTime = (Button) findViewById(R.id.create_sport_begin_time_button);
	        mPickTime.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
	        
	        // add a click listener to the button
	        mPickTime.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                showDialog(TIME_DIALOG_ID);
	            }
	        });

	        mEndTimeDisplay = (EditText) findViewById(R.id.create_sport_end_time_field);
	        mEndPickTime = (Button) findViewById(R.id.create_sport_end_time_button);
	        mEndPickTime.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
	        
	        // add a click listener to the button
	        mEndPickTime.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                showDialog(END_TIME_DIALOG_ID);
	            }
	        });
	        
		// get the current date
	     final Calendar c = Calendar.getInstance();
	     mYear = c.get(Calendar.YEAR);
	     mMonth = c.get(Calendar.MONTH);
	     mDay = c.get(Calendar.DAY_OF_MONTH);
	     mHour = c.get(Calendar.HOUR_OF_DAY);
	     mMinute = c.get(Calendar.MINUTE);
	     mEndHour = c.get(Calendar.HOUR_OF_DAY);
	     mEndMinute = c.get(Calendar.MINUTE);
	     
	     updateDisplay();
		 updateTimeDisplay();
		 updateEndTimeDisplay();
		 
		 Spinner spinner = (Spinner) findViewById(R.id.createsporttype);
		 spinner.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
		 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
		         this , R.array.create_sport_array, android.R.layout.simple_spinner_item);
		 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 spinner.setAdapter(adapter);
		 spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
		 spinnerValue.add(spinner.getSelectedItem().toString());
		 Button submit =  (Button) findViewById(R.id.create_sport_submit);
	     submit.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xC6930A));
	     submit.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	Bundle bundle = getIntent().getExtras();
	            	EditText event = (EditText)findViewById(R.id.create_sport_name);
	            	String eventName = event.getText().toString().trim();
	            	String sport = spinnerValue.get(spinnerValue.size() - 1) ;
	            	int startMonth = mMonth + 1;
	            	String start = mYear + "-"+ startMonth + "-" + mDay;
	            	String beginTime = mTimeDisplay.getText().toString();
	            	String endTime = mEndTimeDisplay.getText().toString();
	            	if(!eventName.equals("")){
		            	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		            	nameValuePairs.add(new BasicNameValuePair("userName",bundle.getString("uName")));
		            	nameValuePairs.add(new BasicNameValuePair("location",bundle.getString("location")));
		            	nameValuePairs.add(new BasicNameValuePair("name",eventName));
		            	nameValuePairs.add(new BasicNameValuePair("date",start));
		            	nameValuePairs.add(new BasicNameValuePair("beginTime",beginTime));
		            	nameValuePairs.add(new BasicNameValuePair("endTime",endTime));
		            	nameValuePairs.add(new BasicNameValuePair("type",sport));
		            	String result = "";
		        		InputStream is = null;
		            	
		            	try{
		        			//TODO add username to the bundle and redirect them to the home screen!
		        		        HttpClient httpclient = new DefaultHttpClient();
		        		        HttpPost httppost = new HttpPost("http://gtplay.webatu.com/addEvent.php");
		        		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        		        HttpResponse response = httpclient.execute(httppost);
		        		        HttpEntity entity = response.getEntity();
		        		        is = entity.getContent();
		        		        //Log.e("-----------", spinnerValue.get(spinnerValue.size() - 1));
		        		        //code to redirect on successful signup
		        		        Bundle b = new Bundle();
		                		b.putString("uName", bundle.getString("uName"));	
		                		Intent myintent = new Intent(CreateNewEvent.this,MainPage.class);
		                		myintent.putExtras(bundle);
		                		CreateNewEvent.this.startActivity(myintent);
		                		finish();
		                		//end of redirect code
		                		
		        		}catch(Exception e){
		        		        Log.e("log_tag", "Error in http connection "+e.toString());
		        		}
	            	}else{
	            		Context context = getApplicationContext();
	            		CharSequence text = "Please Insert in an Event Name";
	            		int duration = Toast.LENGTH_SHORT;

	            		Toast toast = Toast.makeText(context, text, duration);
	            		toast.show();
	            		
	            	}
	            }
	        });
	        
	        
	}
	
	
    public class MyOnItemSelectedListener implements OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
           spinnerValue.add(parent.getItemAtPosition(pos).toString()); 
           
        }

        public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
	
	 private DatePickerDialog.OnDateSetListener mDateSetListener =
         new DatePickerDialog.OnDateSetListener() {

             public void onDateSet(DatePicker view, int year, 
                                   int monthOfYear, int dayOfMonth) {
                 mYear = year;
                 mMonth = monthOfYear;
                 mDay = dayOfMonth;
                 updateDisplay();
             }
         };
         
      // the callback received when the user "sets" the time in the dialog
     	 private TimePickerDialog.OnTimeSetListener mTimeSetListener =
     	     new TimePickerDialog.OnTimeSetListener() {
     	         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
     	             mHour = hourOfDay;
     	             mMinute = minute;
     	             updateTimeDisplay();
     	         }
     	     };
      
     	 // the callback received when the user "sets" the time in the dialog
         	 private TimePickerDialog.OnTimeSetListener mEndTimeSetListener =
         	     new TimePickerDialog.OnTimeSetListener() {
         	         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
         	             mEndHour = hourOfDay;
         	             mEndMinute = minute;
         	             updateEndTimeDisplay();
         	         }
         	     };
     	     
     	     
         @Override  
    	 public void onBackPressed() { 
        	 
    		 NewEventGroup.group.back();  
    	     return;  
    	 }
         
      // updates the date in the TextView
 	    private void updateDisplay() {
 	        mDateDisplay.setText(
 	            new StringBuilder()
 	                    // Month is 0 based so add 1
 	                    .append(mMonth + 1).append("-")
 	                    .append(mDay).append("-")
 	                    .append(mYear).append(" "));
 	    }
 	    
 	 	// updates the time we display in the TextView
 	 	  private void updateTimeDisplay() {
 	 	      mTimeDisplay.setText(
 	 	          new StringBuilder()
 	 	                  .append(pad(mHour)).append(":")
 	 	                  .append(pad(mMinute)));
 	 	  }
 	 	  
 	 	// updates the time we display in the TextView
 	 	  private void updateEndTimeDisplay() {
 	 	      mEndTimeDisplay.setText(
 	 	          new StringBuilder()
 	 	                  .append(pad(mEndHour)).append(":")
 	 	                  .append(pad(mEndMinute)));
 	 	  }

 	 	  private static String pad(int c) {
 	 	      if (c >= 10)
 	 	          return String.valueOf(c);
 	 	      else
 	 	          return "0" + String.valueOf(c);
 	 	  }
 	    
	
 	   @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case DATE_DIALOG_ID:
	            return new DatePickerDialog(getParent(),
	                        mDateSetListener,
	                        mYear, mMonth, mDay);
	        case TIME_DIALOG_ID:
	            return new TimePickerDialog(getParent(),
	                    mTimeSetListener, mHour, mMinute, false);
	        case END_TIME_DIALOG_ID:
	        	return new TimePickerDialog(getParent(),
	                    mEndTimeSetListener, mEndHour, mEndMinute, false);
	        }
	        return null;
	    }
 	   

 	  
 	
}
